﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;

namespace Alisoft.SIP
{
    public class RestConnector : IRestConnector 
    {
        private String sipAppKey;// sip_appkey

        private String sipAppSecret;// sip_appsecret

        /// <summary>
        /// 
        /// </summary>
        public string AppKey
        {
            get
            {
                return sipAppKey;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public string AppSecret
        {
            get
            {
                return sipAppSecret;
            }
        }

        #region IRestConnector Members

        /// <summary>
        ///     调用SIP API
        /// </summary>
        /// <param name="sipAPIname">
        ///     要调用的API名称，例如：alisoft.udb.getUserId
        /// </param>
        /// <param name="sipAPIUrl">
        ///     正式环境:         http://sip.alisoft.com/sip/rest,
        ///     测试、开发环境： http://sipdev.alisoft.com/sip/rest
        /// </param>
        /// <param name="parameters">
        ///     请求参数，例如：{a=1,b=2}
        /// </param>
        /// <param name="method">
        ///     POST、GET两种方式，参考Constants.HTTP_METHOD_POST、Constants.HTTP_METHOD_GET
        /// </param>
        /// <param name="needSign">
        ///     是否需要签名，true需要/false不需要
        /// </param>
        /// <returns></returns>
        public SipResult Invoke(string sipAPIname, string sipAPIUrl, Dictionary<string, object> parameters, string method, bool needSign)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 查询某个sessionid对应的用户是否登录(绑定)
        /// </summary>
        /// <param name="sipServiceUrl"></param>
        /// <param name="sessionId">
        ///     endUser 在ISV应用中的唯一用户标识，注意：不同于ISP的用户标识!
        /// </param>
        /// <param name="sipAPIname">
        ///     绑定用户时，所属的api_name是什么，绑定于同一ISP下的任意API均属于已绑定。
        /// </param>
        /// <param name="sipTokenType">
        ///     可选值，session 或者 request
        /// </param>
        /// <returns></returns>
        public bool IsLogin(String sipServiceUrl, String sessionId,
			String sipAPIname, String sipTokenType) 
        {
		    SortedDictionary<String, string> parameters = new SortedDictionary<String, string>();

		    parameters.Add(Constants.PARAMETER_APPKEY, AppKey);
		    parameters.Add(Constants.PARAMETER_TOKEN_TYPE, sipTokenType);
		    parameters.Add(Constants.PARAMETER_APINAME, sipAPIname);
		    parameters.Add(Constants.PARAMETER_SESSIONID, sessionId);
		    parameters.Add(Constants.PARAMETER_SERVICE_COMMAND, "islogin");
		    parameters.Add(Constants.PARAMETER_TIMESTAMP, 
                DateTime.Now.ToString(Constants.SIP_TIMESTAMP_FORMATER)) ;
		    parameters.Add(Constants.PARAMETER_SIGN, SignatureUtil.Signature(parameters,
				    AppSecret));

		    SipResult result = this.SendRequest(sipServiceUrl, parameters, 
				    Constants.HTTP_METHOD_POST);

		    return SipStatus.SUCCESS.getCode().equals(result.getStatus());
        }

        /// <summary>
        /// </summary>
        /// <param name="sipServiceUrl"></param>
        /// <param name="sessionId">
        ///     最终用户在ISV应用中的唯一用户标识，不同于ISP的用户标识
        /// </param>
        /// <param name="sipAPIname">
        ///     绑定用户时，所属的api_name是什么，绑定于同一ISP下的任意API均属于已绑定。
        /// </param>
        /// <returns></returns>
        public bool UnbindUser(string sipServiceUrl, string sessionId, string sipAPIname)
        {
            throw new NotImplementedException();
        }

        #endregion


        private SipResult SendRequest(String url, SortedDictionary<String, String> parameters,
			String method) 
         {

		    String queryString = (null == parameters) ? "" : delimit(parameters.entrySet());

            HttpWebRequest request = new HttpWebRequest();

            request.Method = method;

		    HttpURLConnection conn = (HttpURLConnection) new URL(url)
				    .openConnection();
		    conn.setRequestMethod(method);
		    conn.setDoOutput(true);
		    conn.connect();
		    conn.getOutputStream().write(queryString.getBytes());
		    BufferedReader reader = new BufferedReader(new InputStreamReader(conn
				    .getInputStream(), this.getChareset(conn.getContentType())));

		    String code = conn.getHeaderField(Constants.HTTP_SIP_STATUS);

		    StringBuffer resonpseText = new StringBuffer();

		    if (SipStatus.SUCCESS.getCode().equals(code)) {
			    String line;
			    while ((line = reader.readLine()) != null) {
				    resonpseText.append(line);
			    }
			    reader.close();
		    } else if (SipStatus.NEED_BINDUSER.getCode().equals(code)) {
			    resonpseText.append(conn
					    .getHeaderField(Constants.HEADER_SIP_ISP_LOGINURL));
		    } else {
			    resonpseText.append(conn
					    .getHeaderField(Constants.HEADER_SIP_ERROR_MESSAGE));
		    }

		    conn.disconnect();

		    return new SipResult(code, resonpseText.toString());
    	}


        /// <summary>
        ///     获取字符集，默认为UTF-8
        /// </summary>
        /// <param name="contentType"></param>
        /// <returns></returns>
        private String getChareset(String contentType)
        {
            int i = contentType == null ? -1 : contentType.IndexOf("charset=") ;

            return i == -1 ? Constants.CHARACTER_ENCODING : contentType.Substring(i + 8);
        }


        //private String Delimit(Collection<Map.Entry<String, Object>> entries)
        //{
            //if (entries == null || entries.size() <= 0) {
            //    return "";
            //}

            //StringBuilder buffer = new StringBuilder();
            //for (Map.Entry<String, ?> entry : entries) {
            //    buffer.append("&");
            //    Object value = entry.getValue();
            //    buffer.append(entry.getKey()).append("=").append(
            //            SipUtil.encodeURL(value));
            //}
            //buffer.deleteCharAt(0);// 去掉多余的&
        //    return buffer.ToString();
        //}
    }
}
